<template>
  <n-card :bordered="false" class="proCard table">
    <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset" />
    <BasicTable 
      :columns="columns" 
      :request="loadDataTable" 
      @fetch-success="fetchSuccess" 
      @edit-end="cellEditEnd"
      @update:checked-row-keys="onCheckedRow" 
      ref="actionRef" 
      :actionColumn="actionColumn" 
      :row-key="(row) => row.id"
      :scroll-x="1000">
      <!-- 表格上方左侧的位置 -->
      <template #tableTitle>
        <n-space>
          <!-- 批量删除 -->
          <n-button strong secondary type="error" @click="removeRows">
            批量删除
          </n-button>
        </n-space>
      </template>
    </BasicTable>
  </n-card>
</template>
<script setup>
import { h, reactive, ref, unref } from 'vue'
import { getHospSetPageList, deleteHospSet, batchRemoveHospSet, lockHospSet, updateHospSet } from '@/api/hospset'
import { BasicForm, useForm } from '@/components/Form'
import { BasicTable, TableAction } from '@/components/Table'
import { createListColumns, schemas, createActions } from './columns';
import { useDialog, useMessage } from 'naive-ui';

const dialog = useDialog()
const message = useMessage()
const actionRef = ref(null)
const currentIndex = ref(1)
// 选中的行
const selections = ref([]);
// 分页参数
const defalutParams = () => {
  return {
    hosname: null,
    hoscode: null,
  };
};
const params = reactive(defalutParams())

// 注册表单
const [register, { setProps }] = useForm({
  gridProps: { cols: 3 },
  showAdvancedButton: false,
  schemas,
});
// 表格列属性
const columns = createListColumns({
  currentIndex() {
    return unref(currentIndex);
  },
  switchStatus: async (row) => {
    const { id, status } = row;
    const update = status === 1 ? 0 : 1;
    try {
      await lockHospSet(id, update)
      row.status = update;
    } catch (error) {
      row.status = status
    }
  },
});

// 表格操作列属性
const currentEditKeyRef = ref('');
const actionColumn = reactive({
  width: 140,
  title: '操作',
  key: 'action',
  fixed: 'right',
  align: 'center',
  render(record) {
    return h(TableAction, {
      showLabel: false,
      actions: createActions(record, { handleSave, handleEdit, handleDelete, handleCancel }),
    });
  },
});


// 数据请求
const loadDataTable = async (res) => {
  return await getHospSetPageList({ ...res, ...params });
}
function fetchSuccess() {
  // 数据请求成功，设置索引
  currentIndex.value =
    (actionRef.value.pagination.current - 1) *
    actionRef.value.pagination.pageSize;
}
// 表格选中行事件
function onCheckedRow(rowKeys) {
  selections.value = rowKeys;
}

// 刷新表格
function reloadTable() {
  actionRef.value.reload();
}

// 查询提交方法
function handleSubmit(values) {
  Object.assign(params, values);
  reloadTable();
}

// 查询重置方法
function handleReset() {
  Object.assign(params, defalutParams());
  reloadTable();
}

// 单元格编辑提交事件
const cellEditEnd = async ({ record, index, key, value }) => {
  const param = {
    id: record.id
  }
  param[key] = value
  try {
    await updateHospSet(param)
    message.success('保存成功')
  } catch (error) {
    console.log(error);
  }
}

// 整行编辑保存事件
const handleSave = async (record) => {
  const pass = await record.onEdit?.(false, true);
  if (pass) {
    currentEditKeyRef.value = '';
    const { id, hosname, hoscode, apiUrl, contactsName, contactsPhone } = record;
    // 提交更新
    try {
      await updateHospSet({ id, hosname, hoscode, apiUrl, contactsName, contactsPhone })
      message.success('保存成功')
    } catch (error) {
      console.log(error);
    }
  }
}

// 开启整行编辑事件
const handleEdit = (record) => {
  currentEditKeyRef.value = record.key;
  record.onEdit?.(true);
}

// 删除事件
const handleDelete = (record) => {
  dialog.info({
    title: '提示',
    content: `您想删除：${record.hosname}`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      await deleteHospSet(record.id)
      reloadTable();
    },
    onNegativeClick: () => { },
  });
}

// 取消整行编辑事件
const handleCancel = (record) => {
  currentEditKeyRef.value = '';
  record.onEdit?.(false, false);
}

// 批量删除事件
const removeRows = () => {
  const ids = unref(selections);
  if (ids.length === 0) {
    message.warning('请至少勾选一列');
    return;
  }
  dialog.warning({
    title: '提示',
    content: `您要删除: ${ids}`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      await batchRemoveHospSet(ids);
      reloadTable();
    },
    onNegativeClick: () => {},
  });
}
</script>
